package manage.service;

import m.common.model.util.ModelCheckUtil;
import m.common.model.util.ModelUpdateUtil;
import m.common.service.Service;
import m.system.cache.CacheUtil;
import m.system.db.TransactionManager;
import m.system.exception.MException;
import m.system.util.DateUtil;
import m.system.util.GenerateID;
import m.system.util.StringUtil;
import manage.dao.AdminAssistDao;
import manage.dao.AdminLoginDao;
import manage.model.AdminAssist;
import manage.model.AdminLogin;
import manage.model.StatusModel;

import java.util.*;

public class AdminAssistService extends Service {

    public String save(AdminAssist model, String password) throws Exception {
        if(!password.equals(model.getPassword())){
            throw new MException(this.getClass(),"两次输入的密码不一致");
        }
        ModelCheckUtil.checkNotNull(model,"username","orgGroup.oid");
        ModelCheckUtil.checkUniqueCombine(model, new String[]{"admin.oid","username"},"账号已存在");
        String msg;
        TransactionManager tm=new TransactionManager();
        try{
            tm.begin();
            if(StringUtil.isSpace(model.getOid())){
                model.setOid(GenerateID.generatePrimaryKey());
                model.setCreateDate(new Date());
                model.setStatus(StatusModel.Status_Enable);
                model.setPassword(StringUtil.toMD5(model.getPassword()));
                ModelUpdateUtil.insertModel(model);
                msg="保存成功";
            }else{
                if(StringUtil.isSpace(model.getPassword())){
                    ModelUpdateUtil.updateModel(model, "realname","orgGroup.oid");
                }else{
                    model.setPassword(StringUtil.toMD5(model.getPassword()));
                    ModelUpdateUtil.updateModel(model, "realname","orgGroup.oid","password");
                }
                msg="修改成功";
            }
            tm.commit();
        }catch(Exception e){
            tm.rollback();
            throw e;
        }
        return msg;
    }
    private final Map<String,Date> errorDate= new HashMap<>();
    private final Map<String,Integer> errorNum= new HashMap<>();
    private void errorVerify(String username) throws MException{
        Date date=errorDate.get(username);
        Integer num=errorNum.get(username);
        if(null==date|| DateUtil.add(date, Calendar.HOUR_OF_DAY, 1).getTime()<new Date().getTime()){
            errorDate.put(username, new Date());
            errorNum.put(username, 1);
        }else if(null!=num&&num<10){
            errorNum.put(username, num+1);
        }else{
            throw new MException(this.getClass(),"操作频繁,请稍后再试.");
        }
    }
    public AdminAssist loginVerification(AdminAssist model) throws Exception{
        if(StringUtil.isSpace(model.getAdmin().getUsername())){
            throw new MException(this.getClass(),"登录账号不能为空!");
        }else if(StringUtil.isSpace(model.getUsername())){
            throw new MException(this.getClass(),"账号不能为空!");
        }else if(StringUtil.isSpace(model.getPassword())){
            throw new MException(this.getClass(),"密码不能为空!");
        }else{
            String admin_oid=getDao(AdminLoginDao.class).getUserOid4Username(model.getAdmin().getUsername());
            String user_oid=getDao(AdminAssistDao.class).getUserOid(admin_oid,model.getUsername(),model.getPassword());
            if(StringUtil.isSpace(admin_oid)||StringUtil.isSpace(user_oid)){
                errorVerify(model.getUsername());
                throw new MException(this.getClass(),"账号或者密码错误!");
            }else{
                AdminLogin admin= CacheUtil.get(AdminLogin.class,admin_oid);
                model= CacheUtil.get(AdminAssist.class,user_oid);
                model.setAdmin(admin);
                if("9".equals(model.getStatus())||"9".equals(admin.getStatus())){
                    throw new MException(this.getClass(),"账号已被停用!");
                }
                if(!getService(AdminGroupService.class).verifyOrgGroup(admin.getOid(),model.getOrgGroup().getOid())){
                    throw new MException(this.getClass(),"账号已不在登录部门，请联系主账号修改。");
                }
                model.setToken(UUID.randomUUID().toString());
                ModelUpdateUtil.updateModel(model, "token");
                return model;
            }
        }
    }
    /**
     * 更新最后登录时间和ip
     *  admin
     *  ip
     *  MException
     */
    public void updateLastInfo(AdminAssist admin, String ip) throws MException {
        admin.setLastLoginTime(new Date());
        admin.setLastLoginIp(ip);
        if(null==admin.getLoginCount()){
            admin.setLoginCount(1);
        }else{
            admin.setLoginCount(admin.getLoginCount()+1);
        }
        ModelUpdateUtil.updateModel(admin, "lastLoginTime","lastLoginIp","loginCount");
    }
}
